﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;

using WebImageResizer.ImageTools;

namespace WebImageResizer.ImageTool.Wpf
{
	public class WpfImageTool : NativeImageTool
	{
		#region Instance Methods

		public override byte[] Encode(Bitmap source, ImageFormat imageFormat)
		{
			if (imageFormat == ImageFormat.Png)
			{
				return EncodeBitmap(new PngBitmapEncoder(), source);
			}

			if (imageFormat == ImageFormat.Gif)
			{
				return EncodeBitmap(new GifBitmapEncoder(), source);
			}

			if (imageFormat == ImageFormat.Jpeg)
			{
				return EncodeBitmap(new JpegBitmapEncoder(), source);
			}

			if (imageFormat == ImageFormat.Tiff)
			{
				return EncodeBitmap(new TiffBitmapEncoder(), source);
			}

			return base.Encode(source, imageFormat);
		}

		#endregion

		#region Class Methods

		private static byte[] EncodeBitmap(BitmapEncoder bitmapEncoder, Bitmap bitmap)
		{
			BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
				IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

			using (MemoryStream ms = new MemoryStream())
			{
				bitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapSource));
				bitmapEncoder.Save(ms);
				return ms.ToArray();
			}
		}

		#endregion
	}
}